﻿using CIS.DB;
using System;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;

namespace CIS.Extension
{
	public class Program
	{
		static void Main(string[] args)
		{
			BatchSendMail().Wait();
		}

		public async static Task BatchSendMail()
		{
			CISEntities dbContext = new CISEntities();

			var mailServer = await dbContext.SysMailServerMaster.AsNoTracking()
					.OrderBy(x => x.Sort)
					.ThenByDescending(x => x.UpdateDate)
					.FirstOrDefaultAsync(x => x.Status == "正常");

			if (mailServer != null)
			{
				MailSender sender = new MailSender(mailServer.MailServer);
				MailAddress from = new MailAddress(mailServer.Mail);
				MailAddress to = new MailAddress(mailServer.Mail);
				//MailAddress to = new MailAddress("526041267@qq.com");

				var compareValue = DateTime.Now.AddMinutes(-30);

				var sql = dbContext.SysUserMaster.Where(x => x.Status == "暂停" &&
							!x.HasSend &&
							x.CreateDate > new DateTime(2020, 1, 1) &&
							DateTime.Compare(x.CreateDate.Value, compareValue) < 0);

				var list = await sql.ToListAsync();

				foreach (var user in list)
				{
					MailMessage message = new MailMessage();
					message.IsBodyHtml = true;
					message.Subject = "汇同会议系统注册提醒通知";
					message.Body = "<p>管理员，你好</p>" +
							"<p>邮箱为<strong>" + user.Mail + "</strong>的账号目前处于<strong>暂停</strong>状态。</p>" +
							"<p>请登录系统管理后台查看详情。</p><p>汇同会议系统</p>" + 
							"<p>" + DateTime.Now.ToString("yyyy年MM月dd日") + "</p>";
					message.To.Add(to);

					var strMsg = sender.SendMail(from, message, mailServer.Password);
					if (string.IsNullOrEmpty(strMsg))
					{
						Console.WriteLine(user.Mail);
						user.HasSend = true;
					}
					else
					{
						Console.WriteLine(strMsg);
					}
				}

				await dbContext.SaveChangesAsync();
			}
		}
	}
}